import { Component, OnInit,} from '@angular/core';
import { Location} from '@angular/common';
import { ProblemRelatedService} from '../problem-related.service';
import { Response} from '@angular/http';
import {GlobalService} from "../../global.service";

@Component({
  selector: 'app-problems',
  templateUrl: './problems.component.html',
  styleUrls: ['./problems.component.css']
})
export class ProblemsComponent implements OnInit {

  setsCode:string;//题库code
  problems:Problem[];
  problemCode:string = '-1';
  problemSet:ProblemSet = new ProblemSet;
  problem:Problem = new Problem;
  judgeInfo:JudgeInfo = new JudgeInfo;
  submitFlag:boolean = false;
  judgeLines:JudgeLine[] = [];
  originCode:string;
  totalScore:number;//总分数
  currentCompile:string;
  compiles:any;

  contentClass:string = 'col-sm-12 col-sm-12';

  url:string = this.location.path();

  //控制前台界面显示数据
  showTabFlag:boolean = true;
  //控制按钮是否可点击
  canClick:boolean = false;

  constructor(
    public location:Location,
    private problemRelatedService:ProblemRelatedService,
    private globalService:GlobalService,
  ) { }

  ngOnInit() {
    this.getSetsCode();

    /**
     * 展开题目集展开子菜单
     */
    let li = document.getElementById("li");
    li.setAttribute('class','active');

    let user = this.globalService.getCurrentUser();
    console.log("user:",user);
    if (user!=null){
      this.canClick = true;
    }
  }

  onTabChange(event){
    console.log(event.index);
  }

  getSetsCode(){
    console.log("Code1:");
    let url = this.url;
    let start = this.url.lastIndexOf('problem-sets/') + 13;
    let end = this.url.lastIndexOf('/problems');
    this.setsCode = url.slice(start,end);
    console.log(this.setsCode);
    this.globalService.problemSetCode = this.setsCode;
    //拿到SetsCode后查看是否带有问题ID
    this.getProblemId();
  }

  getProblemId(){
    console.log("problemCode2:");
    let url = this.url;
    let start = this.url.lastIndexOf('problems/') + 9;
    //不等于-1代表后面接的有id
    if (url.lastIndexOf('problems/')!= -1){
      this.problemCode = url.slice(start,url.length);
    }
    console.log(this.problemCode);
    if(this.problemCode!= '-1'){
      this.showTabFlag = false;
    }

    //然后执行查找所有题集中的问题
    this.getProblemsBySetsCode(this.problemCode);
  }

  getProblemsBySetsCode(problemCode){
      let problemSetInfo = {code:this.setsCode};
      // 当是显示单个问题时无需加载
      this.problemSet.problems = [];
      this.totalScore = 0;
      this.problemRelatedService.getProblemsBySetsCode(problemSetInfo)
        .subscribe((res:Response)=>{
          let response = res.json();
          console.log("problemRelatedService方法返回的数据是3:");
          this.problemSet = response.value;
          console.log(this.problemSet);
          //如果题目code不为空那么就拿到problem
          if(problemCode!='-1'){
            this.getProblemByCode(problemCode);
          }
          //计算所有题的分数和
          this.getTotalScore(this.problemSet.problems);
          //给编译器赋值
          this.setOriginCode(this.problemSet.originCode);
        });
  }

  /**
   * 计算所有题的分数和
   * @param data
   */
  getTotalScore(data){
    let totalScore = 0;
    for (let index of data){
        totalScore += index.score;
    }
    this.totalScore = totalScore;
  }

  /**
   * 给编译器赋值
   * @param origins
   */
  setOriginCode(origins){
    //origins类似:"Gcc,Java,"
    let originList = origins.split(',');
    console.log(originList);
    this.currentCompile = originList[0];
    this.judgeInfo.compile = originList[0];
    originList.pop();//删除最后一个空白数据
    this.compiles = originList;
  }


  getProblemByCode(code){
    let temp = this.problemSet.problems;
    for (let problem of temp){
      if (problem.code == code){
        this.problem = problem;
      }
    }
    console.log("hello5");
    console.log(this.problem);
  }

  saveOriginCode(){
    console.log("输入的代码是:");
    console.log(this.judgeInfo.originCode);
    this.originCode = this.judgeInfo.originCode;
    this.judgeInfo.problemCode = this.problemCode;
    this.judgeInfo.name = this.problem.name;
    this.judgeInfo.problemSetCode  = this.setsCode;
    this.judgeInfo.userCode = this.globalService.getCurrentUser().code;
    this.judgeInfo.creator = this.globalService.getCurrentUser().code;
    this.judgeInfo.compile = this.currentCompile;
    console.log(this.judgeInfo);
    this.originCode = this.originCode.replace(/ /g,"&nbsp;");
    this.originCode = this.originCode.replace(/\n/g,"<br/>");
    console.log(this.originCode);
    this.problemRelatedService.saveOriginCode(this.judgeInfo)
      .subscribe((res:Response)=>{
        let response = res.json();
        console.log(response);
        this.judgeLines = [];
        if (response.success){
          console.log("保存成功!");
          this.judgeInfo.code = response.value.code;
          this.judgeInfo.createTime = response.value.createTime;
          this.judgeInfo.runTime = response.value.runTime;
          this.judgeInfo.status = response.value.status;
          this.judgeInfo.statusName = response.value.statusName;
          this.judgeInfo.score = response.value.score;
          this.submitFlag = true;
          this.judgeInfo.remark = "";
        }else{
          alert(response.msg);
        }
      });
  }

  refresh(){
    let _this = this;
    this.problemRelatedService.findJudgeInfoByCode({code:this.judgeInfo.code})
      .subscribe((res:Response)=>{
        console.log(res.json());
        _this.judgeLines = [];
        _this.judgeInfo.statusName = res.json().value.statusName;
        _this.judgeInfo.score = res.json().value.score;
        _this.judgeInfo.runTime = res.json().value.runTime;
        _this.judgeInfo.remark = res.json().value.remark;
        res.json().value.lines.forEach(function (item) {
          _this.judgeLines.push({
            name:item.name,
            remark:item.remark,
            status:item.status,
            statusName:item.statusName,
            runTime:item.runTime,
            runMemory:parseInt(item.runMemory/1024+''),
          });
        })
      });
  }

  hideDetail(){
    this.submitFlag = false;
    this.judgeInfo.remark = "";
  }

}

class ProblemSet{
  code:string;
  company:string;
  createTime:string;
  creator:string;
  dataStatus:string;
  id:string;
  name:string;
  operType:string;
  originCode:string;
  problems:Problem[];
  properties:any;
  status:number;
  statusName:string;
  type:number;
  typeName:string;
  updateTime:string;
  updator:string;
}

class Problem{
  author:string;
  code:string;
  company:string;
  createTime:string;
  creator:string;
  dataStatus:number;
  degree:number;
  describe:string;
  describeHtml:string;
  id:string;
  limitMoney:number;
  limitTime:number;
  name:string;
  operType:string;
  properties:any;
  score:number;
  status:number;
  statusName:string;
  testDataCode:string;
  updateTime:string;
  updator:string;
}

export class JudgeInfo{
  code:string;
  name:string;
  problemCode:string;//code
  problemSetCode:string;
  originCode:string;//代码
  compile:string;//编译器
  userCode:string;
  creator:string;
  createTime:any;
  runTime:any;
  status:any;
  statusName:any;
  score:any;
  remark:string;
}

class JudgeLine{
  name:string;
  remark:string;
  status:any;
  statusName:any;
  runTime:any;
  runMemory:any;
}
